<?php 
defined('C5_EXECUTE') or die("Access Denied.");

class ProjectestateSearchBlockController extends BlockController {

    var $pobj;
    
    const pkgHandle = 'project_estate';
    protected $btTable = 'btprojectestatesearch';
    protected $btInterfaceWidth = "400";
    protected $btInterfaceHeight = "170";
	protected $btCacheBlockRecord = false;
    protected $btCacheBlockOutput = false;
    protected $btCacheBlockOutputOnPost = false;
    protected $btCacheBlockOutputForRegisteredUsers = false;
    protected $btCacheBlockOutputLifetime = 0;
    
    public $title = "";
    public $ctID = "";
    public $buttonText = ">";
    public $baseSearchPath = "";
    public $cssClass = "project_search_result";
    public $resultsURL = "";
	public $mainTypes = null;
	public $searchDesc = 'Select by a type to get the project you are interested';
	public $noResult = 'Sorry, there are no results that match your query, please try with another keyword.';
    
    protected $hColor = '#EFE795';
    
    public function on_page_view() {
        $html = Loader::helper('html');	
//        $b = $this->getBlockObject();
//        $bv = new BlockView();
//        $bv->setBlockObject($b);
//        $this->addHeaderItem('<link rel="stylesheet" type="text/css" href="'.$bv->getBlockURL().'/css/projectestate.css" />');
        Loader::library('controller', $pkgHandle);
    }
    
    public function highlightedMarkup($fulltext, $highlight) {
        $this->hText = $fulltext;
        $this->hHighlight = str_replace(array('"', "'", "&quot;"), '', $highlight); // strip the quotes as they mess the regex
        $this->hText = @preg_replace("#$this->hHighlight#i", '<span style="background-color:'.$this->hColor.';">$0</span>', $this->hText);
        return $this->hText;
    }
    
    public function highlightedExtendedMarkup($fulltext, $highlight) {
        $text = @preg_replace("#\n|\r#", ' ', $fulltext);
        
        $matches = array();
        $highlight = str_replace(array('"', "'", "&quot;"), '', $highlight); // strip the quotes as they mess the regex
        
        $regex = '([a-z|A-Z|0-9|\.|_|\s]{0,45})'.$highlight.'([a-z|A-Z|0-9|\.|_|\s]{0,45})';
        preg_match_all("#$regex#i", $text, $matches);
        
        if (! empty($matches[0])) {
            $body_length = 0;
            $body_string = array();
            foreach ($matches[0] as $line) {
                $body_length += strlen($line);
                
                $body_string[] = $this->highlightedMarkup($line, $highlight);
                
                if ($body_length > 150)
                    break;
            }
            if (! empty($body_string))
                return @implode("....", $body_string);
        }
    }
    
    /** 
     * Used for localization. If we want to localize the name/description we have to include this
     */
    public function getBlockTypeDescription() {
        return t("Add a search box to your site.");
    }
    
    public function getBlockTypeName() {
        return t("Project Estate Search");
    }
    
    public function getJavaScriptStrings() {
        return array('search-title'=>t('Please enter a valid search title.'));
    }
    
    function __construct($obj = null) {
        parent::__construct($obj);
        if ($this->title == '') {
            $this->title = t("Search");
        }
		Loader::model("collection_types");
		Loader::model('attribute/categories/collection');
    }
    
    public function indexExists() {
        $db = Loader::db();
        $numRows = $db->GetOne('select count(cID) from PageSearchIndex');
        return ($numRows > 0);
    }
    
    function view() {
    	$translate = Loader::helper('translate');
        $c = Page::getCurrentPage();
        //auto target is the form action that is used if none is explicity set by the user
        $autoTarget = $c->getCollectionPath();		
		// If the page is vietnamese
		$firstOption = 'Search by';
		$indLang = 0;
		if ($c->getCollectionAttributeValue('Vietnamese_menu')){
			$firstOption = $translate->projectLanguage('select');
			$this->mainTypes = array('none' => t($firstOption), 
										'projectType' => $translate->projectLanguage('type'),
										'projectLocation' => $translate->projectLanguage('location'),
										/*'projectPriceRange' => t('Price Range'),*/ 
										/*'projectNumberRoom' => $translate->projectLanguage('number-of-room'),*/
										'projectKeyword' => $translate->projectLanguage('keyword'));
			$indLang = 1;
			$this->noResult = 'Xin lỗi, không tìm thấy kết quả phù hợp với truy vấn của bạn, mời bạn thử lại từ khóa khác.';
			$this->searchDesc = $translate->projectLanguage('search-desc');
		}
		else{
			$this->mainTypes = array('none' => t($firstOption), 
									'projectType' => t('Type'),
									'projectLocation' => t('Location'),
									/*'projectPriceRange' => t('Price Range'), 
									'projectNumberRoom' => t('Number Of Room'),*/
									'projectKeyword' => t('Keyword'));
		}
        /* 
         * This code is weird. I don't know why it's here or what it does
         
         if( is_array($_REQUEST['search_paths']) ){
         foreach($_REQUEST['search_paths'] as $search_path){
         $autoTarget=str_replace('search_paths[]='.$search_path,'',$autoTarget);
         $autoTarget=str_replace('search_paths%5B%5D='.$search_path,'',$autoTarget);
         }
         }
         $autoTarget=str_replace('page='.$_REQUEST['page'],'',$autoTarget);
         $autoTarget=str_replace('submit='.$_REQUEST['submit'],'',$autoTarget);
         $autoTarget=str_replace(array('&&&&','&&&','&&'),'',$autoTarget);
         */

        $resultTargetURL = ($this->resultsURL != '') ? $this->resultsURL : $autoTarget;
        $this->set('resultTargetURL', $resultTargetURL);
        
        //run query if display results elsewhere not set, or the cID of this page is set
        $cArray = null;
        if (!empty($_GET['projectMain'])) {
            $cArray = $this->do_search();
        }
        $nh = Loader::helper('navigation');
        $this->set('nh', $nh);
        $this->set('cArray', $cArray);
        // Project types
        $ak = CollectionAttributeKey::getByHandle('projectestate_types');
        $akc = $ak->getController();
        $options = $akc->getOptions();
        $opts = array();
        $opts['0'] = t($firstOption);
        foreach ($options as $opt) {
        	$vals = split('::', $opt->getSelectAttributeOptionValue());			
            $opts[$opt->getSelectAttributeOptionID()] = $vals[$indLang];
        }
        $this->set('types', $opts);
        // Project location
        $ak = CollectionAttributeKey::getByHandle('projectestate_locations');
        $akc = $ak->getController();
        $options = $akc->getOptions();
        $opts = array();
        $opts['0'] = t($firstOption);
        foreach ($options as $opt) {
            $vals = split('::', $opt->getSelectAttributeOptionValue());			
            $opts[$opt->getSelectAttributeOptionID()] = $vals[$indLang];;
        }
        $this->set('locations', $opts);
        // Number of Room
        $ak = CollectionAttributeKey::getByHandle('projectestate_numberofrooms');
        $akc = $ak->getController();
        $options = $akc->getOptions();
        $opts = array();
        $opts['0'] = t($firstOption);
        foreach ($options as $opt) {
            $vals = split('::', $opt->getSelectAttributeOptionValue());			
            $opts[$opt->getSelectAttributeOptionID()] = $vals[$indLang];
        }
        $this->set('numberRooms', $opts);
        // Price Range
        $ak = CollectionAttributeKey::getByHandle('projectestate_pricerange');
        $akc = $ak->getController();
        $options = $akc->getOptions();
        $opts = array();
        $opts['0'] = t($firstOption);
        foreach ($options as $opt) {
            $vals = split('::', $opt->getSelectAttributeOptionValue());			
            $opts[$opt->getSelectAttributeOptionID()] = $vals[$indLang];
        }
        $this->set('priceRanges', $opts);
		$this->set('title', $this->title);
        $this->set('buttonText', $this->buttonText);
        $this->set('baseSearchPath', $this->baseSearchPath);
        $this->set('cssClass', $this->cssClass);
		$this->set('mainTypes', $this->mainTypes);
		$this->set('searchDesc', $this->searchDesc);
		$this->set('noResult', $this->noResult);
    }
    
    function save($data) {
        $args['title'] = isset($data['title']) ? $data['title'] : '';
        $args['buttonText'] = isset($data['buttonText']) ? $data['buttonText'] : '';
        $args['baseSearchPath'] = isset($data['baseSearchPath']) ? $data['baseSearchPath'] : '';
        $args['ctID'] = isset($data['ctID']) ? $data['ctID'] : '';
        if ($args['baseSearchPath'] == 'OTHER' && intval($data['searchUnderCID']) > 0) {
            $customPathC = Page::getByID(intval($data['searchUnderCID']));
            if (!$customPathC)
                $args['baseSearchPath'] = '';
            else
                $args['baseSearchPath'] = $customPathC->getCollectionPath();
        }
        if (trim($args['baseSearchPath']) == '/' || strlen(trim($args['baseSearchPath'])) == 0)
            $args['baseSearchPath'] = '';
        $args['resultsURL'] = ($data['externalTarget'] == 1 && strlen($data['resultsURL']) > 0) ? trim($data['resultsURL']) : '';
        parent::save($args);
    }
    
    //public $reservedParams = array('page=', 'query=', 'search_paths[]=', 'submit=', 'search_paths%5B%5D=');
    
    function do_search() {
        Loader::model('page_list');
        $db = Loader::db();
		
        $pl = new PageList();
        $c = Page::getCurrentPage();
        if (is_object($c)) {
            $this->cID = $c->getCollectionID();
        }
		if ($this->ctID) {
			$pl->filterByCollectionTypeID($this->ctID);
		}
		
        if (isset($_GET['projectMain']) && ! empty($_GET['projectMain'])) {
        	if ($c->getCollectionAttributeValue('Vietnamese_menu')){
        		$this->title = isset($this->mainTypes[$_GET['projectMain']]) ? 'Tìm theo ' . $this->mainTypes[$_GET['projectMain']] : 'Search Project';
			}
			else{
        		$this->title = isset($this->mainTypes[$_GET['projectMain']]) ? 'Search by ' . $this->mainTypes[$_GET['projectMain']] : 'Search Project';
			}
		}
        // Filter by location, type
        if (isset($_GET['projectType']) && ! empty($_GET['projectType'])) {
	        $pl->filterByProjectestateType(intval($_GET['projectType']));
		}
        if (isset($_GET['projectLocation']) && ! empty($_GET['projectLocation'])) {
            $pl->filterByProjectestateLocation(intval($_GET['projectLocation']));
        }
        if (isset($_GET['projectNumberRoom']) && ! empty($_GET['projectNumberRoom'])) {
            $pl->filterByProjectestateNumberofroom(intval($_GET['projectNumberRoom']));        	
		}
		if (isset($_GET['projectKeyword']) && ! empty($_GET['projectKeyword'])) {
			$pl->filterByKeywords("%".$_GET['projectKeyword']."%");        	
		}
		
		$columns = $db->MetaColumns(CollectionAttributeKey::getIndexedSearchTable());
		if (isset($columns['AK_EXCLUDE_PAGE_LIST'])) {
			$pl->filter(false, '(ak_exclude_page_list = 0 or ak_exclude_page_list is null)');
		}
		// Filter by Language
		$lang = $c->getCollectionAttributeValue('Vietnamese_menu') ? '1' : '0';
		$pl->filterByVietnameseMenu($lang);		
		
        $pages = $pl->getPage();
        //var_dump($pages->getQuery());
        $this->set('pl', $pl);
        $this->set('do_search', true);
        return $pages;
    }        
}
?>
